package com.hellloop.pim.alphabeat.network;

import java.io.*;
import java.util.HashMap;

public class PIMServer {

	private static final int DEFAULT_PORT_NUMBER = 44215;
	
	private PIMServerMessageProcessor processor;

	private PIMServerConnectionThread serverConnectionThread;

private int _currentRoomId = 100;
	private HashMap roomList;

	public PIMServer() {
		this( new PIMServerMessageProcessor() );
		roomList = new HashMap();
	}

	public PIMServer(PIMServerMessageProcessor processor) {
		this.processor = processor;
		processor.setPIMServer(this);
	}

	public void processLoginRequest(PIMConnectionMsg reqMsg, int clientId) {
		PIMConnectionMsg msg = new PIMConnectionMsg();
		msg.setOprType( PIMConnectionMsg.LoginResponse );
		msg.setUserId( String.valueOf(clientId) );
		msg.setUserName( reqMsg.getUserName() );
		serverConnectionThread.sendMessageToOneClient(msg, clientId);
	}
	
	public void processCreateRoom(String roomName) {
		if( !roomList.containsKey(roomName) ) {
			roomList.put(roomName, _currentRoomId);
			
			PIMRoomMsg msg = new PIMRoomMsg( PIMRoomMsg.CreateRoomResponse, String.valueOf(_currentRoomId) );
			//should update room list to another player
			serverConnectionThread.sendMessageToAllClients(msg);
			
			_currentRoomId+=10;//dump generate
		}
		else {
			//should send error
		}		
	}
	
	public void processJoinRoom(String playerId, String roomName) {
		if( roomList.containsKey(roomName) ) {
			String roomId = roomList.get(roomName).toString();
			
			PIMRoomMsg msg = new PIMRoomMsg( PIMRoomMsg.JoinRoomResponse, roomId );
			//should update room list to another player
			serverConnectionThread.sendMessageToAllClients(msg);
		}
		else {
			//should send error
		}
	}
	
	public void openConnection(int port) throws IOException {
		if (port <= 0)
			port = DEFAULT_PORT_NUMBER;
		serverConnectionThread = new PIMServerConnectionThread(this, port, processor);
		serverConnectionThread.openConnection();
	}

	public void closeConnection() throws IOException {
		serverConnectionThread.closeConnection();
	}

	public void sendMessageToAllClients(PIMMessage message) {
		serverConnectionThread.sendMessageToAllClients(message);
	}

	public void printClientList() {
		String[] clientList = serverConnectionThread.getClientList();
		for (String socket : clientList) {
			System.out.println(socket);
		}
	}

	public int getClientCount() {
		return serverConnectionThread.getClientCount();
	}

	public static void main(String[] args) throws IOException {		
		PIMServer pimServ = new PIMServer();
		pimServ.openConnection(-1);
	}

	public void processGenerateSentence(String roomId) {
		PIMGameMsg msg = new PIMGameMsg();
		msg.setOprType( PIMGameMsg.SentenceResponse );
		msg.setSentenses("FixTest:HardCode:How I can do:Bye bye!@#");		
		serverConnectionThread.sendMessageToAllClients(msg);		
	}
}
